package com.server.questionbank.snframe.controller.QuestionBan;

import com.server.questionbank.snframe.domain.Homework.TExercises;
import com.server.questionbank.snframe.domain.Ollama.OllamaRespone;
import com.server.questionbank.snframe.domain.QuestionBank.DTO.ExercisesDto;
import com.server.questionbank.snframe.domain.QuestionBank.Exercises;
import com.server.questionbank.snframe.domain.QuestionBank.Question;
import com.server.questionbank.snframe.domain.ResDTO.PageResult;
import com.server.questionbank.snframe.domain.ResDTO.ResponseResult;
import com.server.questionbank.snframe.domain.User.UansQueRecord;
import com.server.questionbank.snframe.domain.User.UansRecord;
import com.server.questionbank.snframe.domain.dto.GradingResult;
import com.server.questionbank.snframe.service.CourseService.TQuestionService;
import com.server.questionbank.snframe.service.OllamaService.OllamaService;
import com.server.questionbank.snframe.service.OllamaService.TestQuestion.TestQuestionService;
import com.server.questionbank.snframe.service.QuestionBank.ExercisesService;
import com.server.questionbank.snframe.service.QuestionBank.UansQueRecordService;
import com.server.questionbank.snframe.service.QuestionBank.UansRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/questionban")
public class ExercisesController {

    @Autowired
    private ExercisesService exercisesService;

    @Autowired
    private TQuestionService tQuestionService;

    @Autowired
    private TestQuestionService testQuestionService;

    @Autowired
    private UansQueRecordService uansQueRecordService;

    @Autowired
    private UansRecordService uansRecordService;

    @Autowired
    private OllamaService ollamaService;

    @GetMapping("/list")
    public ResponseResult<PageResult<TExercises>> getQuestionBanList(
            @RequestParam(required = false) String type,
            @RequestParam Map<String, String> sort) {
        PageResult<TExercises> questionBanList = exercisesService.getQuestionBanList(type, sort);
        return ResponseResult.success(questionBanList);
    }


    @GetMapping("/id")
    public ResponseResult<TExercises> selectById(@RequestParam Long exercisesId){
        TExercises selectById = exercisesService.selectById(exercisesId);
        if (selectById == null) return ResponseResult.error();
        return ResponseResult.success(selectById);
    }

    /**
     * Ai改卷
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Transactional
    @PostMapping("/testQuestion")
    public ResponseResult<GradingResult> testQuestion(@RequestBody Map<String, Object> map){
        try {
            // 1. 参数提取与验证（增强版）
            if (map == null || !map.containsKey("userAnswer")) {
                return ResponseResult.error(400, "参数错误：缺少userAnswers字段");
            }

            Object answersObj = map.get("userAnswer");
            if (!(answersObj instanceof List)) {
                return ResponseResult.error(400, "参数错误：userAnswers必须是数组");
            }

            List<String> userAnswers = new ArrayList<>();
            for (Object item : (List<?>) answersObj) {
                if (item != null) {
                    userAnswers.add(item.toString());
                }
            }

            Long userId = parseLongSafely(map.get("userId"));
            Long exercisesId = parseLongSafely(map.get("exercisesId"));

            if (userId == null || exercisesId == null) {
                return ResponseResult.error(400, "参数错误：userId或exercisesId格式不正确");
            }

            // 2. 获取题目列表
            List<Question> questionList = tQuestionService.getQuestionByExercisesId(exercisesId);
            if (questionList == null || questionList.isEmpty()) {
                return ResponseResult.error(404, "未找到对应题目");
            }

            // 3. 检查答案数量匹配
            if (userAnswers.size() != questionList.size()) {
                return ResponseResult.error(400,
                        String.format("答案数量不匹配（需要%d个，收到%d个）",
                                questionList.size(), userAnswers.size()));
            }

            // 计算满分（每题10分）
            float fullMark = questionList.size() * 10.0f;

            // 3. 初始化答题记录
            UansRecord uansRecord = initUserAnswerRecord(userId, exercisesId, fullMark);
            uansRecordService.createRecord(uansRecord);
            Long recordId = uansRecord.getRecordId();

            // 4. 处理每个问题并计算得分
            float totalScore = processQuestionsAndCalculateScore(questionList, userAnswers, recordId);

            // 5. 更新总分
            updateTotalScore(uansRecord, totalScore);

            // 6. 构建返回结果
            GradingResult gradingResult = buildGradingResult(totalScore, questionList);

            String qu = "题目";
            String huida = "用户回答";
            String cankdaan = "参考答案";
            String fenshu = "分数";
            Flux<OllamaRespone> pjia = ollamaService.sendGeneralMessage(new OllamaRespone("评价以下题目的回答：" + "题目：" + qu + "学生回答：" +  huida + "参考答案：" +  cankdaan + "得分：" +  fenshu,null));
            pjia.collectList()
                    .subscribe(
                            list -> {
                                list.forEach(response -> {
                                    System.out.println(response.getMessage());
                                });
                            },
                            error -> {
                                System.err.println("处理失败: " + error.getMessage());
                            },
                            () -> {
                                System.out.println("所有响应处理完成");
                            }
                    );

            //            System.out.println(ResponseResult.success(gradingResult));
            return ResponseResult.success(gradingResult);


        } catch (Exception e) {
            return ResponseResult.error(500, "服务器处理错误: " + e.getMessage());
        }
    }

    private Long parseLongSafely(Object value) {
        try {
            return value != null ? Long.valueOf(value.toString()) : null;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * Ai组卷功能查询
     *
     * @param params
     * @return
     */
    @GetMapping("/search")
    public ResponseResult<PageResult<TExercises>> searchQuestions(ExercisesDto params){
        System.out.println(params);
        return ResponseResult.success((PageResult<TExercises>) exercisesService.searchQuestions(params));
    }


    /**
     * 批量获取题目信息
     */
    @GetMapping("/exam")
    public ResponseResult<List<Exercises>> getBatchExercisesWithQuestions(
            @RequestParam String exercisesIds)
    {
        try{
            // 参数空值检查
            if (exercisesIds == null || exercisesIds.trim().isEmpty()) {
                return ResponseResult.error("参数exerciseIds不能为空");
            }
            Long[] ids = Arrays.stream(exercisesIds.split(","))
                    .map(Long::valueOf)
                    .toArray(Long[]::new);
            System.out.println(ids);
            List<Exercises> exercisesList = exercisesService.findBatchExercisesWithQuestions(ids);
            return ResponseResult.success(exercisesList);
        }catch (Exception e){
            System.out.println(e);
            return ResponseResult.error(e.getMessage());
        }
    }







    private UansRecord initUserAnswerRecord(Long userId, Long exercisesId, float fullMark) {
        UansRecord record = new UansRecord();
        record.setUserId(userId);
        record.setExercisesId(exercisesId);
        record.setMarkMan("AI");
        record.setFullMark(fullMark);
        record.setScore(0f); // 初始分数为0
        return record;
    }

    private float processQuestionsAndCalculateScore(List<Question> questions, List<String> userAnswers, Long recordId) {
        float totalScore = 0f;

        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);
            String userAnswer = userAnswers.get(i); // 获取对应索引的用户答案
            System.out.println(userAnswer);

            // 计算单个问题得分
            float questionScore = calculateSingleQuestionScore(question, userAnswer);

            // 记录单个问题答题情况
            saveQuestionAnswerRecord(question, userAnswer, questionScore, recordId);

            // 累加总分
            totalScore += questionScore;
            totalScore = formatScore(totalScore);
        }

        return totalScore;
    }

    private float calculateSingleQuestionScore(Question question, String userAnswer) {
        float rawScore = 0;
        try {
            rawScore = testQuestionService.getScore(question, userAnswer) * 10;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return formatScore(rawScore);
    }

    private void saveQuestionAnswerRecord(Question question, String userAnswer,
                                          float score, Long recordId) {
        UansQueRecord queRecord = new UansQueRecord();
        queRecord.setRecId(question.getRecId());
        queRecord.setScore(score);
        queRecord.setUserAnswer(userAnswer);
        queRecord.setMarkMan("AI");
        queRecord.setFullMark(10); // 每题满分10分
        queRecord.setRecordId(recordId);
        uansQueRecordService.addAnswerRecords(queRecord);
    }

    private void updateTotalScore(UansRecord record, float totalScore) {
        record.setScore(totalScore);
        uansRecordService.updateRecord(record);
    }

    private GradingResult buildGradingResult(float totalScore, List<Question> questions) {
        GradingResult result = new GradingResult();
        result.setScore(totalScore);
        result.setQuestion(questions);
        // result.setFeedback(); // 可以在此添加AI评语
        return result;
    }

    private float formatScore(float score) {
        return Float.parseFloat(String.format("%.2f", score));
    }

















}